package async;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author fei.fang
 * @date 2021/8/27
 **/
public class ThreadPoolText {

    public static class MTask implements Runnable{

        private String name;

        public MTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("正在执行：" + Thread.currentThread().getId() + ", name=" + name);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor exec = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(), Executors.defaultThreadFactory()) {
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                System.out.println("执行开始：" + ((MTask) r).name);
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                System.out.println("执行结束：" + ((MTask) r).name);
            }

            @Override
            protected void terminated() {
                System.out.println("线程池退出");
                ;
            }
        };

        for (int i = 0; i < 5; i++) {
            MTask mTask = new MTask("task-name-" + i);
            exec.execute(mTask);
            Thread.sleep(10);
        }

        exec.shutdown();
    }
}
